package cn.exrick.service.impl;

import cn.exrick.common.exception.XmallException;
import cn.exrick.mapper.TbFeedbackCatMapper;
import cn.exrick.mapper.TbFeedbackMapper;
import cn.exrick.pojo.TbFeedback;
import cn.exrick.pojo.TbFeedbackCat;
import cn.exrick.pojo.common.DataTablesResult;
import cn.exrick.service.FeedbackService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FeedbackServiceImpl implements FeedbackService{

    @Autowired
    private TbFeedbackMapper tbFeedbackMapper;
    @Autowired
    private TbFeedbackCatMapper tbFeedbackCatMapper;

    @Override
    public DataTablesResult getFeedbackPage(int draw, int start, int length, String search, Integer feedbackCatId,
                                            String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();

        //分页执行查询返回结果
        PageHelper.startPage(start / length + 1, length);
        PageHelper.orderBy(orderCol + " " + orderDir);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("search", search);
        if(null != feedbackCatId){
            paramsMap.put("feedbackCatId", feedbackCatId);
        }
        paramsMap.put("minDate", minDate);
        paramsMap.put("maxDate", maxDate);

        List<TbFeedback> list = tbFeedbackMapper.selectByPage(paramsMap);
        PageInfo<TbFeedback> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int) pageInfo.getTotal());
        result.setRecordsTotal((int) pageInfo.getTotal());

        result.setDraw(draw);
        result.setData(list);

        return result;
    }

    @Override
    public int add(TbFeedback tbFeedback) {
        TbFeedbackCat tbFeedbackCat = tbFeedbackCatMapper.selectByPrimaryKey(tbFeedback.getFeedbackCatId());
        if(null == tbFeedbackCat){
            throw new XmallException("反馈分类不存在");
        }
        int result = tbFeedbackMapper.insert(tbFeedback);
        if(1 != result){
            throw new XmallException("提交反馈失败");
        }
        return result;
    }

}
